package com.mission.schedule.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.R;
import com.mission.schedule.activity.MainActivity;
import com.mission.schedule.activity.NewFriendsActivity;
import com.mission.schedule.activity.QDFXDetailActivity;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.NoteTypeBean;
import com.mission.schedule.bean.qd606.NoteShareBean;
import com.mission.schedule.bean.qd606.NoteTitleDetailBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.entity.ScheduleTable;
import com.mission.schedule.utils.DateUtil;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.StringUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 下载和同步清单
 * Created by liwei on 2017/3/2.
 */

public class NoteService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
        App.getHttpQueues().cancelAll("downnote");
        App.getHttpQueues().cancelAll("downnotetype");
        App.getHttpQueues().cancelAll("downnoteshare");
    }


    SharedPrefUtil sharedPrefUtil;
    String UserId = "";
    String downtime = "2017-01-01";
    private void saveFriend(NoteShareBean.ListBean bean){
        boolean isSave = false;
        List<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> itemsBeanList = App.getDBcApplication().getAllNewFriendData(UserId, false);
        for (NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean : itemsBeanList) {
            if (itemsBean.pname.equals(bean.pname)) {
                isSave = true;
                break;
            }
        }
        if (!isSave) {
            NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean = new NewFriendsActivity.newFriendBean.PageBean.ItemsBean();
            itemsBean.pname = bean.pname;
            itemsBean.uid = Integer.valueOf(UserId);
            itemsBean.puid = Integer.valueOf(bean.puid);
            itemsBean.pimgs = bean.pimg;
            itemsBean.id = App.getDBcApplication().getNFMinId() - 1;
            itemsBean.createTime = DateUtil.nowTime();
            itemsBean.changeTime = DateUtil.nowTime();
            itemsBean.remark = "";
            itemsBean.remark1 = "";
            itemsBean.type = 0;
            App.getDBcApplication().saveNewFriendData(itemsBean, 1);
        }
    }
    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

        sharedPrefUtil = new SharedPrefUtil(getApplication(),
                ShareFile.USERFILE);
        UserId = sharedPrefUtil.getString(getApplicationContext(),
                ShareFile.USERFILE, ShareFile.USERID, "");
        downtime = sharedPrefUtil.getString(
                getApplication(), ShareFile.USERFILE,
                ShareFile.UPDATENOTESETTIME, "2017-01-01%2B00:00:00");
        isPull = false;
        if (sharedPrefUtil.getString(getApplication(),
                ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (intent != null) {
                        if (intent.getIntExtra("loadType", 0) == 0) {
                            downNoteData();
                            downNoteType();
                            downNoteState();
                            downNoteTypeData();
                        } else if (intent.getIntExtra("loadType", 0) == 1) {
//                            updateBeanToJson();
                            sysNoteType();
                        } else if (intent.getIntExtra("loadType", 0) == 2) {
                            isPull = true;
//                            downNoteHongdian();
//                            downNoteState();
                            downNoteTypeData();
                        }
                    }
                }
            }).start();
        }
    }

    boolean isPull = false;

    /**
     * 清单分类下载
     */
    public void downNoteType() {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.清单分类下载,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String result) {
                                    if (!TextUtils.isEmpty(result)) {
                                        try {
                                            Gson gson = new Gson();
                                            NoteTypeBean bean = gson.fromJson(result, NoteTypeBean.class);
                                            if (bean.status == 0) {
                                                sharedPrefUtil
                                                        .putString(
                                                                getApplication(),
                                                                ShareFile.USERFILE,
                                                                ShareFile.UPDATENOTESETTIME,
                                                                bean.downTime.replace('T', ' '));
                                                List<NoteTypeBean.ListBean> list = bean.list;

                                                if (list != null) {
                                                    Collections.sort(list, new Comparator<NoteTypeBean.ListBean>() {
                                                        @Override
                                                        public int compare(NoteTypeBean.ListBean lhs, NoteTypeBean.ListBean rhs) {
                                                            return rhs.changeTime.compareTo(lhs.changeTime);
                                                        }
                                                    });
                                                    for (int i = 0; i < list.size() - 1; i++) {
                                                        for (int j = list.size() - 1; j > i; j--) {
                                                            if (list.get(j).localId == list.get(i).localId) {
                                                                list.remove(j);
                                                            }
                                                        }
                                                    }
                                                    for (NoteTypeBean.ListBean listBean : list) {
                                                        App.getDBcApplication().saveNoteTypeData(listBean);
                                                    }
                                                }
                                            }
                                        } catch (JsonSyntaxException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.d("TAG", "error:" + volleyError.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("uId", UserId);// "52432"
                            return map;
                        }
                    };
                    stringRequest.setTag("downnotetype");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.queues.add(stringRequest);
                }
            }).start();
        }
    }

    /**
     * 清单分类同步
     */
    public void sysNoteType() {
        final List<NoteTypeBean.ListBean> listBeanList = App.getDBcApplication().getAllNoteTypeData(UserId, true);
        if (listBeanList.size() > 0) {
            JSONObject jsonObject = new JSONObject();
            try {
                JSONArray jsonArray = new JSONArray();
                for (NoteTypeBean.ListBean bean : listBeanList) {
                    JSONObject object = new JSONObject();
                    object.put("id", bean.id);
                    object.put("orderId", bean.orderId);
                    object.put("remark", bean.remark);
                    object.put("remark1", bean.remark1);
                    object.put("localId", bean.localId);
                    object.put("changeTime", bean.changeTime);
                    object.put("content", bean.content);
                    object.put("styleId", bean.styleId);
                    object.put("uid", bean.uid);
                    object.put("updateState", App.getDBcApplication().getNoteTypestate(UserId, bean.localId));
                    jsonArray.put(object);
                }
                jsonObject.put("TbUserDetailListType", jsonArray);
                HttpUtils httpUtils = new HttpUtils(10000);
                RequestParams params = new RequestParams();
                params.addBodyParameter("data", jsonObject.toString());
                httpUtils.send(HttpMethod.POST, URLConstants.清单分类同步, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onFailure(HttpException e, String msg) {
                                Log.e("TAG", "清单分类同步失败" + msg);
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {
                                for (NoteTypeBean.ListBean listBean : listBeanList) {
                                    App.getDBcApplication().updateNoteTypeState(listBean.localId, 0);
                                }
                            }
                        });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 清单下载
     */
    private void downNoteData() {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.清单和清单标题下行,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String result) {
                                    if (!TextUtils.isEmpty(result)) {
                                        try {
                                            Gson gson = new Gson();
                                            NoteTitleDetailBean bean = gson.fromJson(result, NoteTitleDetailBean.class);
                                            if (bean.status == 0) {
                                                sharedPrefUtil
                                                        .putString(
                                                                getApplication(),
                                                                ShareFile.USERFILE,
                                                                ShareFile.UPDATENOTESETTIME,
                                                                bean.downTime.replace('T', ' '));
                                                List<NoteTitleDetailBean.TDelListBean> tDelList = bean.tDelList;
                                                List<NoteTitleDetailBean.ListBean> beanList = bean.list;
                                                List<NoteTitleDetailBean.DelListBean> delList = bean.delList;

                                                if (tDelList != null) {
                                                    boolean isTitleBWL = false;
                                                    for (NoteTitleDetailBean.TDelListBean tDelListBean : tDelList) {
                                                        if (tDelListBean.titles.equals("备忘录")) {
                                                            if (!isTitleBWL) {
                                                                App.getDBcApplication().saveNoteTitleData(tDelListBean);
                                                            }
                                                            isTitleBWL = true;
                                                        } else {
                                                            App.getDBcApplication().saveNoteTitleData(tDelListBean);
                                                        }
                                                    }
                                                }

                                                if (beanList != null) {
                                                    for (NoteTitleDetailBean.ListBean listBean : beanList) {
                                                        if (!listBean.contents.isEmpty()) {
                                                            App.getDBcApplication().saveNoteDetailData(listBean);
                                                        }
                                                    }
                                                }

                                                if (delList != null) {
                                                    for (NoteTitleDetailBean.DelListBean delListBean : delList) {

                                                        App.getDBcApplication().deleteNote(delListBean.type, delListBean.dataId);
                                                    }
                                                }
                                            }
                                        } catch (JsonSyntaxException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.d("TAG", "error:" + volleyError.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("uId", UserId);// "52432"
                            map.put("changeTime", downtime.replace('T', ' '));//downtime.replace('T', ' ')
                            return map;
                        }
                    };
                    stringRequest.setTag("downnote");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.queues.add(stringRequest);
                }
            }).start();
        }
    }

    private void downNoteHongdian(){
        try {
            List<NoteTitleDetailBean.TDelListBean> tDelListBeanList = App.getDBcApplication().getAllNoteTitlesData(UserId, true);

            if (tDelListBeanList != null && tDelListBeanList.size() > 0){
                final JSONObject jsonObject = new JSONObject();
                JSONArray jsonArray = new JSONArray();
                for (NoteTitleDetailBean.TDelListBean bean : tDelListBeanList){
                    if (bean.other1.equals("0")) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("uId", bean.uid);
                        jsonObject1.put("titleId", bean.titleId);
                        jsonArray.put(jsonObject1);
                    }
                }
                jsonObject.put("ly",jsonArray);

                if (jsonObject != null){
                    HttpUtils httpUtils0 = new HttpUtils(5000);
                    RequestParams params0 = new RequestParams();
                    params0.addBodyParameter("data", jsonObject.toString());
                    params0.addBodyParameter("cuId", UserId);
                    httpUtils0.send(HttpMethod.POST, URLConstants.清单留言收藏方下行红点, params0, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                try {
                                    Gson gson = new Gson();
                                    DownCalenderService.ReHod downLoadBean = gson.fromJson(responseInfo.result, DownCalenderService.ReHod.class);
                                    if (downLoadBean.status == 0) {
                                        List<DownCalenderService.ReHod.ListBean> listBeanList = downLoadBean.list;
                                        if (listBeanList != null) {
                                            MainActivity.instance.loadCount();
                                            for (DownCalenderService.ReHod.ListBean bean : listBeanList) {
                                                Date d = DateUtil.parseDateTimeSs(App.getDBcApplication().getNoteTitleChangeTime(bean.titleId));
                                                if (d == null) {
                                                    d = DateUtil.parseDateTimeSs(DateUtil.formatDateTimeSs(new Date()));
                                                }
                                                if (DateUtil.parseDateTimeSs(bean.changeTime.replace('T', ' ')).after(d)) {
                                                    App.getDBcApplication().updateNoteTitleOther1(bean.titleId, UserId, bean.changeTime.replace('T', ' '));
                                                }
                                            }
                                        }
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            Log.e("TAG",s);
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void downNoteState() {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            HttpUtils httpUtils = new HttpUtils(5000);
            RequestParams params = new RequestParams();
            params.addBodyParameter("titleId", "");
            params.addBodyParameter("uId", UserId);
            params.addBodyParameter("type", "0");
            httpUtils.send(HttpMethod.POST, URLConstants.清单留言状态公开方下行, params, new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    if (!TextUtils.isEmpty(responseInfo.result)) {
                        Gson gson = new Gson();
                        downNoteState bean = gson.fromJson(responseInfo.result, downNoteState.class);
                        if (bean.status == 0) {
                            List<downNoteState.ListBean> list = bean.list;
                            if (list != null){
                                for (downNoteState.ListBean listBean: list){
                                    App.getDBcApplication().updateNoteChildState(listBean.titleId,listBean.ccId,listBean.states);
                                }
                            }
                            HttpUtils httpUtils = new HttpUtils(3000);
                            RequestParams params = new RequestParams();
                            params.addBodyParameter("titleId", "");
                            params.addBodyParameter("uId", UserId);
                            params.addBodyParameter("type", "0");
                            httpUtils.send(HttpMethod.POST, URLConstants.清单留言公开方状态表删除通知, params, new RequestCallBack<String>() {
                                @Override
                                public void onSuccess(ResponseInfo<String> responseInfo) {
                                }

                                @Override
                                public void onFailure(HttpException e, String s) {
                                }
                            });
                        }
                    }
                }

                @Override
                public void onFailure(HttpException e, String s) {
                }
            });
        }
    }

    /**
     * 清单被转发下载
     */
    private void downNoteTypeData() {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.清单被转发下载,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String result) {
                                    if (!TextUtils.isEmpty(result)) {
                                        try {
                                            Gson gson = new Gson();
                                            NoteShareBean bean = gson.fromJson(result, NoteShareBean.class);
                                            if (bean.status == 0) {
                                                sharedPrefUtil
                                                        .putString(
                                                                getApplication(),
                                                                ShareFile.USERFILE,
                                                                ShareFile.UPDATENOTESETTIME,
                                                                bean.downTime.replace('T', ' '));
                                                List<NoteShareBean.ListBean> beanList = bean.list;


                                                if (beanList != null) {
                                                    Collections.sort(beanList, new Comparator<NoteShareBean.ListBean>() {
                                                        @Override
                                                        public int compare(NoteShareBean.ListBean lhs, NoteShareBean.ListBean rhs) {
                                                            return Integer.valueOf(lhs.puid) - Integer.valueOf(rhs.puid);
                                                        }
                                                    });
                                                    for (int i = 0; i < beanList.size(); i++) {
                                                        saveFriend(beanList.get(i));
                                                        if (i == 0) {
                                                            NoteTitleDetailBean.TDelListBean tDelListBean = new NoteTitleDetailBean.TDelListBean();
                                                            tDelListBean.titleId = beanList.get(i).titleId;
                                                            tDelListBean.uid = Integer.valueOf(UserId);
                                                            tDelListBean.id = App.getDBcApplication().getTiMinId() - 1;
                                                            tDelListBean.styles = beanList.get(i).style;
                                                            tDelListBean.changeTime = beanList.get(i).changeTime;
                                                            tDelListBean.createTime = beanList.get(i).createTime;
                                                            tDelListBean.localTimes = beanList.get(i).createTime;
                                                            tDelListBean.ltype = 0;
                                                            tDelListBean.orderId = 0;
                                                            tDelListBean.copys = "0";
                                                            tDelListBean.filed = "0";
                                                            tDelListBean.titles = beanList.get(i).titles;// + "@"+beanList.get(i).pname
                                                            tDelListBean.imgPath = beanList.get(i).imgPath;
                                                            tDelListBean.imgUrl = "";
                                                            tDelListBean.nums = "";
                                                            tDelListBean.shareUrl = "";
                                                            if (beanList.get(i).titles.isEmpty()) {
                                                                tDelListBean.remark = "1";
                                                            } else {
                                                                tDelListBean.remark = "0";
                                                            }
                                                            tDelListBean.remark1 = "0";
                                                            tDelListBean.remark2 = "";
                                                            tDelListBean.remark3 = "";
                                                            tDelListBean.remark5 = beanList.get(i).remark3;
                                                            tDelListBean.remark6 = beanList.get(i).remark4;
                                                            tDelListBean.pname = beanList.get(i).pname;
                                                            tDelListBean.puid = Integer.valueOf(beanList.get(i).puid);
                                                            tDelListBean.states = 0;
                                                            tDelListBean.sends = 0;
                                                            tDelListBean.openState = 0;
                                                            tDelListBean.other1 = "1";//1未读

                                                            App.getDBcApplication().saveNoteTitleData(tDelListBean);
                                                            App.getDBcApplication().updateNoteTitleState(tDelListBean.titleId, UserId, 1, false);


                                                            NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean = new NewFriendsActivity.newFriendBean.PageBean.ItemsBean();
                                                            itemsBean.pname = beanList.get(i).pname;
                                                            itemsBean.uid = Integer.valueOf(UserId);
                                                            itemsBean.puid = Integer.valueOf(beanList.get(i).puid);
                                                            itemsBean.pimgs = beanList.get(i).pimg;
                                                            itemsBean.id = App.getDBcApplication().getNFMinId() - 1;
                                                            itemsBean.createTime = DateUtil.nowTime();
                                                            itemsBean.changeTime = DateUtil.nowTime();
                                                            itemsBean.remark = "";
                                                            itemsBean.remark1 = "";
                                                            itemsBean.type = 0;
                                                            App.getDBcApplication().saveNewFriendData(itemsBean, 1);
                                                        } else {
                                                            if (!beanList.get(i).puid.equals(beanList.get(i - 1).puid)) {
                                                                NoteTitleDetailBean.TDelListBean tDelListBean = new NoteTitleDetailBean.TDelListBean();
                                                                tDelListBean.titleId = beanList.get(i).titleId;
                                                                tDelListBean.uid = Integer.valueOf(UserId);
                                                                tDelListBean.id = App.getDBcApplication().getTiMinId() - 1;
                                                                tDelListBean.styles = beanList.get(i).style;
                                                                tDelListBean.changeTime = beanList.get(i).changeTime;
                                                                tDelListBean.createTime = beanList.get(i).createTime;
                                                                tDelListBean.localTimes = beanList.get(i).createTime;
                                                                tDelListBean.ltype = 0;
                                                                tDelListBean.orderId = 0;
                                                                tDelListBean.copys = "0";
                                                                tDelListBean.filed = "0";
                                                                tDelListBean.titles = beanList.get(i).titles;// + "@"+beanList.get(i).pname
                                                                tDelListBean.imgPath = beanList.get(i).imgPath;
                                                                tDelListBean.imgUrl = "";
                                                                tDelListBean.nums = "";
                                                                tDelListBean.shareUrl = "";
                                                                if (beanList.get(i).titles.isEmpty()) {
                                                                    tDelListBean.remark = "1";
                                                                } else {
                                                                    tDelListBean.remark = "0";
                                                                }
                                                                tDelListBean.remark1 = "0";
                                                                tDelListBean.remark2 = "";
                                                                tDelListBean.remark3 = "";
                                                                tDelListBean.remark5 = beanList.get(i).remark3;
                                                                tDelListBean.remark6 = beanList.get(i).remark4;
                                                                tDelListBean.pname = beanList.get(i).pname;
                                                                tDelListBean.puid = Integer.valueOf(beanList.get(i).puid);
                                                                tDelListBean.states = 0;
                                                                tDelListBean.sends = 0;
                                                                tDelListBean.openState = 0;
                                                                tDelListBean.other1 = "1";//1未读

                                                                App.getDBcApplication().saveNoteTitleData(tDelListBean);
                                                                App.getDBcApplication().updateNoteTitleState(tDelListBean.titleId, UserId, 1, false);

                                                                NewFriendsActivity.newFriendBean.PageBean.ItemsBean itemsBean = new NewFriendsActivity.newFriendBean.PageBean.ItemsBean();
                                                                itemsBean.pname = beanList.get(i).pname;
                                                                itemsBean.uid = Integer.valueOf(UserId);
                                                                itemsBean.puid = Integer.valueOf(beanList.get(i).puid);
                                                                itemsBean.pimgs = beanList.get(i).pimg;
                                                                itemsBean.id = App.getDBcApplication().getNFMinId() - 1;
                                                                itemsBean.createTime = DateUtil.nowTime();
                                                                itemsBean.changeTime = DateUtil.nowTime();
                                                                itemsBean.remark = "";
                                                                itemsBean.remark1 = "";
                                                                itemsBean.type = 0;
                                                                App.getDBcApplication().saveNewFriendData(itemsBean, 1);
                                                            }
                                                        }

                                                        NoteTitleDetailBean.ListBean bean1 = new NoteTitleDetailBean.ListBean();
                                                        bean1.titleId = beanList.get(i).titleId;
                                                        bean1.uid = Integer.valueOf(UserId);
                                                        bean1.id = beanList.get(i).id;
                                                        bean1.style = beanList.get(i).style;
                                                        bean1.changetime = beanList.get(i).changeTime;
                                                        bean1.createTime = beanList.get(i).createTime;
                                                        bean1.lType = beanList.get(i).ltype;
                                                        bean1.orderId = beanList.get(i).orderId;
                                                        bean1.endstate = beanList.get(i).endstate;
                                                        bean1.remark = beanList.get(i).remark;
                                                        bean1.contents = beanList.get(i).contents;
                                                        bean1.titles = beanList.get(i).titles;
                                                        bean1.imgPath = beanList.get(i).imgPath;
                                                        bean1.imgUrl = beanList.get(i).imgUrl;
                                                        bean1.cpath = beanList.get(i).cpath + "";
                                                        bean1.curl = beanList.get(i).curl + "";
                                                        bean1.nums = beanList.get(i).nums;
                                                        bean1.shareUrl = beanList.get(i).shareUrl;
                                                        bean1.remark1 = beanList.get(i).remark1;
                                                        bean1.remark2 = beanList.get(i).remark2;
                                                        bean1.remark3 = beanList.get(i).remark5;
                                                        bean1.remark4 = beanList.get(i).remark6;

                                                        App.getDBcApplication().saveNoteDetailData(bean1);
                                                        App.getDBcApplication().updateNoteTitleDetailState(bean1.titleId, bean1.id, UserId, 1, false);

                                                    }
                                                }
                                                MainActivity.instance.updateNoteTitleNoReadNums();
                                                if (isPull) {
                                                    Intent pull = new Intent();
                                                    pull.setAction("pullRecevier");
                                                    getApplication().sendBroadcast(pull);
                                                }
                                                postNoteData();
                                            } else {
                                                if (isPull) {
                                                    Intent pull = new Intent();
                                                    pull.setAction("pullRecevier");
                                                    getApplication().sendBroadcast(pull);
                                                }
                                            }
                                        } catch (JsonSyntaxException e) {
                                            e.printStackTrace();
                                            if (isPull) {
                                                Intent pull = new Intent();
                                                pull.setAction("pullRecevier");
                                                getApplication().sendBroadcast(pull);
                                            }
                                        }
                                    } else {
                                        if (isPull) {
                                            Intent pull = new Intent();
                                            pull.setAction("pullRecevier");
                                            getApplication().sendBroadcast(pull);
                                        }
                                    }
                                }

                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.d("TAG", "error:" + volleyError.toString());
                            if (isPull) {
                                Intent pull = new Intent();
                                pull.setAction("pullRecevier");
                                getApplication().sendBroadcast(pull);
                            }
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("uId", UserId);// "52432"
                            return map;
                        }
                    };
                    stringRequest.setTag("downnoteshare");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.queues.add(stringRequest);
                }
            }).start();
        }
    }


    /**
     * 本地通知是否下行了转发清单
     */
    private void postNoteData() {
        if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.清单转发成功,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String result) {
                                }

                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.d("TAG", "error:" + volleyError.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map = new HashMap<>();
                            map.put("uId", UserId);// "52432"
                            return map;
                        }
                    };
                    stringRequest.setTag("postnote");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
                    App.queues.add(stringRequest);
                }
            }).start();
        }
    }


    private void updateBeanToJson() {
        //标题
        List<NoteTitleDetailBean.TDelListBean> tDelListBeanList = App.getDBcApplication().getAllNoteTitlesData(UserId, true);
        List<NoteTitleDetailBean.ListBean> listBeanList = App.getDBcApplication().getAllNoteDetailData(UserId, true);
        JSONObject tDelListBeanListjsonObject = new JSONObject();
        try {
            JSONArray tDelListBeanListjsonArray = new JSONArray();
            for (NoteTitleDetailBean.TDelListBean bean : tDelListBeanList) {
                JSONObject js = new JSONObject();
                js.put("id", bean.id);
                js.put("titleId", bean.titleId);
                js.put("uid", bean.uid);
                js.put("titles", bean.titles);
                js.put("imgPath", bean.imgPath);
                js.put("imgUrl", bean.imgUrl);
                js.put("shareUrl", bean.shareUrl);
                js.put("filed", bean.filed);
                js.put("nums", bean.nums);
                js.put("copys", bean.copys);
                js.put("styles", bean.styles);
                js.put("ltype", bean.ltype);
                js.put("orderId", bean.orderId);
                js.put("createTime", bean.createTime);
                js.put("changeTime", bean.changeTime);
                js.put("localTimes", bean.localTimes);
                js.put("remark", bean.remark);
                js.put("remark1", bean.remark1);
                js.put("remark2", bean.remark2);
                js.put("remark3", bean.remark3);
                js.put("puid", bean.puid);
                js.put("pname", bean.pname);
                js.put("states", bean.states);
                js.put("sends", bean.sends);
                js.put("openState", bean.openState);
                js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getNoteTitleState(bean.titleId, UserId));
                tDelListBeanListjsonArray.put(js);
            }
            if (tDelListBeanList.size() > 0) {
                tDelListBeanListjsonObject.put("classTitle", tDelListBeanListjsonArray);
            } else {
                tDelListBeanListjsonObject = null;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        //详情
        JSONObject listjsonObject = new JSONObject();
        JSONArray listjsonArray = new JSONArray();
        try {
            for (NoteTitleDetailBean.ListBean bean : listBeanList) {
                JSONObject js = new JSONObject();
                js.put("id", bean.id);
                js.put("titleId", bean.titleId);
                js.put("uid", bean.uid);
                js.put("titles", bean.titles);
                js.put("imgPath", bean.imgPath);
                js.put("imgUrl", bean.imgUrl);
                js.put("shareUrl", bean.shareUrl);
                js.put("contents", bean.contents);
                js.put("nums", bean.nums);
                js.put("style", bean.style);
                js.put("endstate", bean.endstate);
                js.put("lType", bean.lType);
                js.put("orderId", bean.orderId);
                js.put("createTime", bean.createTime);
                js.put("changeTime", bean.changetime);
                js.put("cpath", bean.cpath);
                js.put("curl", bean.curl);
                js.put("remark", bean.remark);
                js.put("remark1", bean.remark1);
                js.put("remark2", bean.remark2);
                js.put("remark3", bean.remark3);
                js.put("remark4", bean.remark4);
                js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getNoteTitleDetailState(bean.titleId, UserId, bean.id));
                listjsonArray.put(js);
            }
            if (listBeanList.size() > 0) {
                listjsonObject.put("class1", listjsonArray);
            } else {
                listjsonObject = null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        uploadNoteData(listjsonObject == null ? "" : listjsonObject.toString(),
                tDelListBeanListjsonObject == null ? "" : tDelListBeanListjsonObject.toString(),tDelListBeanList);
        if (tDelListBeanList != null) {
            uploadGongKaiHongdian(tDelListBeanList);
        }
    }

    /**
     * 系统留言
     */
    private void ly(List<NoteTitleDetailBean.TDelListBean> tDelListBeanList){
        String data = lyJsonStrinf(tDelListBeanList);
        HttpUtils httpUtils = new HttpUtils(2000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("row1", "▶︎ @"+sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERNAME, "")+" 修改了清单内容");
        params.addBodyParameter("row2", "#清单修改#");
        params.addBodyParameter("data", data);
        httpUtils.send(HttpMethod.POST, URLConstants.清单留言同步主留言信息, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    private String lyJsonStrinf(List<NoteTitleDetailBean.TDelListBean> tDelListBeanList){
        JSONObject ly = new JSONObject();
        try {
            JSONArray jsonArray = new JSONArray();
            for (NoteTitleDetailBean.TDelListBean bean : tDelListBeanList){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", -1);
                jsonObject.put("mess", "修改了清单内容!");
                jsonObject.put("updateState", 1);
                jsonObject.put("uid", UserId);
                jsonObject.put("lyUid", UserId);
                jsonObject.put("lyName", sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERNAME, ""));
                jsonObject.put("titleId", bean.titleId);
                jsonObject.put("cId", 0);
                jsonObject.put("localTimes", DateUtil.formatDateTimeSs(new Date()));
                jsonObject.put("type", 1);//0 普通留言 1 系统留言
                jsonObject.put("reamrk1", android.os.Build.MODEL.replace(" ","")+" "+android.os.Build.VERSION.RELEASE);
                jsonObject.put("lyTitleImg", sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERPHOTOPATH, ""));
                jsonObject.put("reamrk", bean.titles);
                jsonObject.put("changeTime",DateUtil.formatDateTimeSs(new Date()));
                jsonArray.put(jsonObject);
            }

            ly.put("ly",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ly.toString();
    }

    private void uploadGongKaiHongdian(List<NoteTitleDetailBean.TDelListBean> tDelListBeanList) {
        for (NoteTitleDetailBean.TDelListBean bean : tDelListBeanList) {
            if (bean.openState == 1) {
                HttpUtils httpUtils = new HttpUtils(3000);
                RequestParams params = new RequestParams();
                params.addBodyParameter("titleId", bean.titleId);
                params.addBodyParameter("uId", bean.uid + "");
                params.addBodyParameter("cuId", UserId + "");
                httpUtils.send(HttpMethod.POST, URLConstants.清单留言公开方公开清单同步通知, params,
                        new RequestCallBack<String>() {

                            @Override
                            public void onFailure(HttpException e, String msg) {
                                Log.e("TAG", "清单同步失败" + msg);
                            }

                            @Override
                            public void onSuccess(ResponseInfo<String> responseInfo) {

                            }
                        });
            }
        }
    }


    /**
     * 上传清单数据
     *
     * @param data
     * @param dataTitle
     */
    private void uploadNoteData(String data, String dataTitle,final List<NoteTitleDetailBean.TDelListBean> tDelListBeanList) {
        HttpUtils httpUtils = new HttpUtils(10000);
        RequestParams params = new RequestParams();
        params.addBodyParameter("data", data);
        params.addBodyParameter("dataTitle", dataTitle);
        httpUtils.send(HttpMethod.POST, URLConstants.清单和清单标题上行, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException e, String msg) {
                        Log.e("TAG", "清单同步失败" + msg);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        if (!TextUtils.isEmpty(responseInfo.result)) {
                            Gson gson = new Gson();
                            noteSynBean bean = gson.fromJson(responseInfo.result, noteSynBean.class);
                            if (bean.status == 0) {
                                ly(tDelListBeanList);
                                List<noteSynBean.TDelListBean> tDeListBeanList = bean.tDelList;

                                //标题同步没有异常
                                List<Integer> errorList = new ArrayList<Integer>();

                                for (noteSynBean.TDelListBean tDeListBean : tDeListBeanList) {
                                    if (tDeListBean.dataState == 1) {//新增
                                        if (tDeListBean.state == 0) {//成功
                                            //修改id和状态值
                                            App.getDBcApplication().updateNoteTitleId(tDeListBean.id, tDeListBean.calendId, UserId);
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.calendId + "", UserId, 0, true);
                                        } else if (tDeListBean.state == 1) {//失败  可以不操作,但是避免意外
                                            //更改状态为1
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, 1, true);
                                        } else if (tDeListBean.state == 2) { //异常
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, -1, true);
                                            errorList.add(tDeListBean.id);
                                        }
                                    } else if (tDeListBean.dataState == 2) {//修改
                                        if (tDeListBean.state == 0) {//成功
                                            //修改该id状态值
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, 0, true);
                                        } else if (tDeListBean.state == 1) {//失败
                                            //更改状态为2
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, 2, true);
                                        } else if (tDeListBean.state == 2) { //异常
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, -1, true);
                                            errorList.add(tDeListBean.id);
                                        }
                                    } else if (tDeListBean.dataState == 3) {//删除
                                        if (tDeListBean.state == 0) {//成功
                                            //删除该id的清单
                                            App.getDBcApplication().deleteNoteTitleData(tDeListBean.id, UserId, true);
                                        } else if (tDeListBean.state == 1) {//失败
                                            //更改状态为3
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, 3, true);
                                        } else if (tDeListBean.state == 2) { //异常
                                            App.getDBcApplication().updateNoteTitleState(tDeListBean.id + "", UserId, -1, true);
                                            errorList.add(tDeListBean.id);
                                        }
                                    }
                                }

                                if (errorList.size() == 0) {

                                    List<noteSynBean.ListBean> listBeans = bean.list;
                                    if (listBeans != null) {
                                        for (noteSynBean.ListBean listBean : listBeans) {

                                            if (listBean.dataState == 1) {//新增
                                                if (listBean.state == 0) {//成功
                                                    //修改id和状态值
                                                    App.getDBcApplication().updateNoteDetailId(listBean.id, listBean.calendId, UserId);
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.calendId, UserId, 0, true);
                                                } else if (listBean.state == 1) {//失败  可以不操作,但是避免意外
                                                    //更改状态为1
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, 1, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, -1, true);
                                                }
                                            } else if (listBean.dataState == 2) {//修改
                                                if (listBean.state == 0) {//成功
                                                    //修改该id状态值
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, 0, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为2
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, 2, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, -1, true);
                                                }
                                            } else if (listBean.dataState == 3) {//删除
                                                if (listBean.state == 0) {//成功
                                                    //删除该id的清单
                                                    App.getDBcApplication().deleteNoteTitledetailData(listBean.id, UserId, true);
                                                } else if (listBean.state == 1) {//失败
                                                    //更改状态为3
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, 3, true);
                                                } else if (listBean.state == 2) { //异常
                                                    App.getDBcApplication().updateNoteTitleDetailState("", listBean.id, UserId, -1, true);
                                                }
                                            }
                                        }
                                    }
                                    sharedPrefUtil.putString(
                                            getApplication(),
                                            ShareFile.USERFILE,
                                            ShareFile.UPDATENOTESETTIME,
                                            bean.downTime.replace("T", " "));

                                }
                            }

                        }

                    }
                });


    }


    public class noteSynBean {

        /**
         * delList : null
         * downTime : 2017-03-07T16:30:44
         * list : [{"id":"-2","calendId":0,"state":2,"mess":"该条数据数据异常，不能正常更新","dataState":2,"downTime":"2017-03-07 16:30:44"}]
         * message : 成功,请联系管理员
         * status : 0
         * tDelList : [{"id":-1,"calendId":72,"state":0,"mess":"","dataState":1,"downTime":"2017-03-07 16:30:44"},{"id":-2,"calendId":73,"state":0,"mess":"","dataState":1,"downTime":"2017-03-07 16:30:44"}]
         */

        public Object delList;
        public String downTime;
        public String message;
        public int status;
        public List<ListBean> list;
        public List<TDelListBean> tDelList;

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public List<TDelListBean> getTDelList() {
            return tDelList;
        }

        public void setTDelList(List<TDelListBean> tDelList) {
            this.tDelList = tDelList;
        }

        public class ListBean {
            /**
             * id : -2
             * calendId : 0
             * state : 2
             * mess : 该条数据数据异常，不能正常更新
             * dataState : 2
             * downTime : 2017-03-07 16:30:44
             */

            public int id;
            public int calendId;
            public int state;
            public String mess;
            public int dataState;
            public String downTime;

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getCalendId() {
                return calendId;
            }

            public void setCalendId(int calendId) {
                this.calendId = calendId;
            }

            public int getState() {
                return state;
            }

            public void setState(int state) {
                this.state = state;
            }

            public String getMess() {
                return mess;
            }

            public void setMess(String mess) {
                this.mess = mess;
            }

            public int getDataState() {
                return dataState;
            }

            public void setDataState(int dataState) {
                this.dataState = dataState;
            }

            public String getDownTime() {
                return downTime;
            }

            public void setDownTime(String downTime) {
                this.downTime = downTime;
            }
        }

        public class TDelListBean {
            /**
             * id : -1
             * calendId : 72
             * state : 0
             * mess :
             * dataState : 1
             * downTime : 2017-03-07 16:30:44
             */

            public int id;
            public int calendId;
            public int state;
            public String mess;
            public int dataState;
            public String downTime;

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getCalendId() {
                return calendId;
            }

            public void setCalendId(int calendId) {
                this.calendId = calendId;
            }

            public int getState() {
                return state;
            }

            public void setState(int state) {
                this.state = state;
            }

            public String getMess() {
                return mess;
            }

            public void setMess(String mess) {
                this.mess = mess;
            }

            public int getDataState() {
                return dataState;
            }

            public void setDataState(int dataState) {
                this.dataState = dataState;
            }

            public String getDownTime() {
                return downTime;
            }

            public void setDownTime(String downTime) {
                this.downTime = downTime;
            }
        }
    }

    private void createNoteType() {
        noteTypeBean(0, "备忘录", 0, 0);
//        noteTypeBean(-1, "收到的", -1, -1);
        noteTypeBean(1, "工作", 1, 1);
        noteTypeBean(2, "生活", 2, 2);
        noteTypeBean(3, "其他", 3, 3);
        noteTypeBean(4, "分类A", 4, 4);
        noteTypeBean(5, "分类B", 5, 5);
        noteTypeBean(6, "分类C", 6, 6);
    }

    private void noteTypeBean(int localId, String name, int orderId, int styleid) {
        NoteTypeBean.ListBean bean = new NoteTypeBean.ListBean();
        bean.id = 0;
        bean.uid = Integer.valueOf(UserId);
        bean.content = name;
        bean.changeTime = DateUtil.formatDateTimeSs(new Date());
        bean.orderId = orderId;
        bean.styleId = styleid;
        bean.localId = localId;
        bean.remark = "";
        bean.remark1 = "";

        App.getDBcApplication().saveNoteTypeData(bean);
    }

    public class downNoteState {

        /**
         * status : 0
         * downTime : 2017-07-19T14:26:11
         * message : 成功
         * list : [{"remark":null,"states":"1","uid":1318776,"id":257,"titleId":"20170719120025035535","ccId":136811,"changeTime":"2017-07-19T14:24:30"}]
         * tDelList : null
         * delList : null
         */

        public int status;
        public String downTime;
        public String message;
        public Object tDelList;
        public Object delList;
        public List<ListBean> list;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public Object getTDelList() {
            return tDelList;
        }

        public void setTDelList(Object tDelList) {
            this.tDelList = tDelList;
        }

        public Object getDelList() {
            return delList;
        }

        public void setDelList(Object delList) {
            this.delList = delList;
        }

        public List<ListBean> getList() {
            return list;
        }

        public void setList(List<ListBean> list) {
            this.list = list;
        }

        public class ListBean {
            /**
             * remark : null
             * states : 1
             * uid : 1318776
             * id : 257
             * titleId : 20170719120025035535
             * ccId : 136811
             * changeTime : 2017-07-19T14:24:30
             */

            public Object remark;
            public String states;
            public int uid;
            public int id;
            public String titleId;
            public int ccId;
            public String changeTime;

            public Object getRemark() {
                return remark;
            }

            public void setRemark(Object remark) {
                this.remark = remark;
            }

            public String getStates() {
                return states;
            }

            public void setStates(String states) {
                this.states = states;
            }

            public int getUid() {
                return uid;
            }

            public void setUid(int uid) {
                this.uid = uid;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getTitleId() {
                return titleId;
            }

            public void setTitleId(String titleId) {
                this.titleId = titleId;
            }

            public int getCcId() {
                return ccId;
            }

            public void setCcId(int ccId) {
                this.ccId = ccId;
            }

            public String getChangeTime() {
                return changeTime;
            }

            public void setChangeTime(String changeTime) {
                this.changeTime = changeTime;
            }
        }
    }
}
